package model

import (
	Mysql "gin/database"
	"gorm.io/datatypes"
)

type Package struct {
	Id      int64          `json:"id" gorm:"column:id"`
	Name    string         `json:"name" gorm:"column:name"`
	Md5     string         `json:"md5" gorm:"column:md5"`
	Type    string         `json:"type" gorm:"column:type"`
	Path    string         `json:"path" gorm:"column:path"`
	Version string         `json:"version" gorm:"column:version"`
	Param   datatypes.JSON `json:"param" gorm:"column:param"`
	Uuid    string         `json:"uuid" gorm:"column:uuid"`
}

// 设置表名
func (Package) TableName() string {
	return "package"
}

// 获取指定文件MD5数据
func (this *Package) GetFileDataByMD5(MD5 string) (fileData Package, err error) {

	result := Mysql.DB.Where("md5 = ?", MD5).First(&this)

	if this.Id == 0 {
		err = result.Error
	} else {
		fileData = *this
	}

	return
}

// 插入文件数据
func (this *Package) Insert() (id int64, err error) {
	result := Mysql.DB.Create(&this)
	id = this.Id
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}

// 通过 Name 查找文件
func (this *Package) SelectFileByName(Name []string) (fileData []Package, err error) {

	result := Mysql.DB.Where("name in (?)", Name).Find(&fileData)

	if result.Error != nil {
		err = result.Error
	}

	return
}

// 通过 Name 删除文件
func (this *Package) RemoveFileByName(Name []string) (err error) {
	result := Mysql.DB.Where("name in (?)", Name).Delete(&this)

	if result.Error != nil {
		err = result.Error
	}
	return
}
